package com.example.administrator.androidui3;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.lang.reflect.Type;
import java.util.List;

public class couseActivity extends AppCompatActivity {
    List<Course> courseList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_couse);
        initData();
        initView();
    }

    private void initView() {
        ListView lvCourses = findViewById(R.id.lv_courses);
        CourseAdapter adapter = new CourseAdapter();
        lvCourses.setAdapter(adapter);

    }

    private void initData() {
        Gson gson = new Gson();
        Type listType = new TypeToken<List<Course>>() {
        }.getType();
        InputStream in = getResources().openRawResource(R.raw.data);
        Reader reader = new InputStreamReader(in);
        courseList = gson.fromJson(reader, listType);


    }

    class CourseAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return courseList.size();
        }

        @Override
        public Object getItem(int position) {
            return courseList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = View.inflate(couseActivity.this, R.layout.list_item,
                    null);

            ImageView imageView = view.findViewById(R.id.iv_course);
            Course course =courseList.get(position);
            if (course.getCourseImage().equals("cc.png")){
                imageView.setImageResource(R.drawable.cc);
            }else if(course.getCourseImage().equals("java.png")){
                imageView.setImageResource(R.drawable.java);

            }
            imageView.setImageResource(R.drawable.cc);
            TextView tvCourseName = view.findViewById(R.id.tv_course_name);

            tvCourseName.setText(course.getCourseName());
            tvCourseName.setText("java");
            return view;
        }
    }
}
